package cn.edu.scnu.semart.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtils {
    private static final String KEY = "SmartSecretKey2025";
//    private static final long EXPIRE = 24 * 60 * 60 * 1000; // 24h

    private static final long EXPIRE = 30L * 24 * 60 * 60 * 1000; // 30天

    public static String createToken(Integer userId, String userType) {
        Date now = new Date();
        return Jwts.builder()
                .setSubject(userId.toString())
                .claim("userType", userType)
                .setIssuedAt(now)
                .setExpiration(new Date(now.getTime() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, KEY)
                .compact();
    }

    public static Integer getUserId(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(KEY)
                .parseClaimsJws(token.replace("Bearer ", ""))
                .getBody();
        return Integer.valueOf(claims.getSubject());
    }

    public static String getUserType(String token) {
        return (String) Jwts.parser()
                .setSigningKey(KEY)
                .parseClaimsJws(token.replace("Bearer ", ""))
                .getBody()
                .get("userType");
    }
}